package com.cloudcode.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudcode.document.DocumentContent;
import com.cloudcode.dto.req.DocumentContentReq;
import com.cloudcode.dto.resp.DocumentContentResp;
import com.cloudcode.repository.DocumentRepository;
import com.cloudcode.repository.DocumentRepositoryPlus;
import com.cloudcode.service.SearchCoreService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author yunst
 * @data 2023/10/23 17:10
 */
@Service
public class SearchCoreServiceImpl implements SearchCoreService {
    @Resource
    private DocumentRepository docRepository;
    @Resource
    private DocumentRepositoryPlus documentRepositoryPlus;

    @Override
    public Page<DocumentContentResp> search(String keyWord, String lastId, Integer size) {
        return documentRepositoryPlus.querySearchAfterTitleAndContent(keyWord, lastId, size);
    }

    @Override
    public void saveDocument(DocumentContentReq documentContentReq) {
        String joinStr = null;
        if (CollUtil.isNotEmpty(documentContentReq.getImg())) {
            joinStr = documentContentReq.getImg().stream().collect(Collectors.joining(";"));
        }

        documentContentReq.getImg().forEach(item -> {

        });
        DocumentContent documentContent = new DocumentContent();
        documentContent.setContent(documentContentReq.getContent());
        documentContent.setType(documentContentReq.getType().getCode());
        documentContent.setCreateTime(System.currentTimeMillis());
        documentContent.setImgUrl(joinStr);
        documentContent.setPath(documentContentReq.getPath());
        documentContent.setTitle(documentContentReq.getTitle());
        documentContent.setId(IdUtil.getSnowflakeNextId());
        documentContent.setCareer(documentContentReq.getCareer());
        docRepository.save(documentContent);
    }

    @Override
    public void delete(String id) {
        docRepository.deleteById(id);
    }

    @Override
    public List<DocumentContentResp> previewList(String keyword, Integer size) {
        return documentRepositoryPlus.querySearchTitle(keyword, size);
    }

}
